﻿using Base.Infrastructure.Dto.Response;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;

namespace Base.Api.Admin.Filters
{
    public class ActionLogAttribute : BaseFilterAttribute
    {
        /// <summary>
        /// 分组
        /// </summary>
        public string? group { get; set; }

        /// <summary>
        /// 行为
        /// </summary>
        public string? name { get; set; }

        /// <summary>
        /// 记录日志 并替换返回值
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            //记录操作日志 两手准备 第一个记录到 本地文件 txt 第二个记录到数据库
            //记录时我得知道你这次是什么操作
            var result = (context.Result as ObjectResult)?.Value;
            if (result is ApiResult)
            {
                string paras = "";
                if (context.HttpContext.Request.Method.ToUpper() == "GET")
                {
                    var keys = context.HttpContext.Request.Query.Keys;
                    foreach (var item in keys)
                    {
                        paras += $"{item}={context.HttpContext.Request.Query[item]};";
                    }
                }
                else
                {
                    var request = context.HttpContext.Request;
                    request.EnableBuffering();
                    if (request.Method.ToLower().Equals("post"))
                    {
                        request.Body.Seek(0, SeekOrigin.Begin);
                        using var reader = new StreamReader(request.Body, Encoding.UTF8);
                        paras = reader.ReadToEnd();
                    }
                }


                var url = context.HttpContext.Request.Path;

                var initResult = result as ApiResult;
                string fileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                System.IO.File.AppendAllText(@"F:\.NET Core\Base(2.0)\" + fileName,
                    $"时间【{DateTime.Now.ToString()}】地址【{url}】IP【{this.GetIp()}】组【{this.group}】,行为【{this.name}】,结果【{initResult?.code}】" +
                    $"消息【{initResult?.message}】参数【{paras}】\r\n\r\n");
            }
            else
            {
                //没有返回结果
            }


        }
    }
}
